package cn.sskxyz.security.resource.config;

import cn.sskxyz.security.core.model.User;
import cn.sskxyz.security.resource.authorization.PermissionValidator;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.FilterInvocation;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

public class RbacAccessDecisionVoter implements AccessDecisionVoter<FilterInvocation> {
    private PermissionValidator permissionValidator;

    public RbacAccessDecisionVoter(PermissionValidator permissionValidator) {
        this.permissionValidator = permissionValidator;
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    public int vote(Authentication authentication, FilterInvocation object, Collection<ConfigAttribute> attributes) {
        HttpServletRequest request = object.getRequest();
        if (authentication.getPrincipal() instanceof User) {
            boolean success = permissionValidator.hasPermission(request.getRequestURI(), (User) authentication.getPrincipal());
            if (success) {
                return AccessDecisionVoter.ACCESS_GRANTED;
            }
        }
        return AccessDecisionVoter.ACCESS_DENIED;
    }
}
